package school.community.controller;

import school.community.dto.CommentDTO;
import school.community.dto.InfoDTO;
import school.community.enums.CommentTypeEnum;
import school.community.exception.CustomizeErrorCode;
import school.community.exception.CustomizeException;
import school.community.service.CommentService;
import school.community.service.InfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

/**
 * Created by codedrinker on 2019/5/21.
 */
@Controller
@Slf4j
public class InfoController {

    @Autowired
    private InfoService infoService;

    @Autowired
    private CommentService commentService;

    @GetMapping("/info/{id}")
    public String info(@PathVariable(name = "id") String id,
                       Model model) {
        Long infoID = null;
        try {
            infoID = Long.parseLong(id);
        } catch (NumberFormatException e) {
            throw new CustomizeException(CustomizeErrorCode.INVALID_INPUT);
        }
        InfoDTO infoDTO = infoService.getById(infoID);
        List<InfoDTO> relatedQuestions = infoService.selectRelated(infoDTO );
        List<CommentDTO> comments = commentService.listByTargetId(infoID, CommentTypeEnum.QUESTION);
        //通过quesion_id来查询这是否是管理员发布的内容
        String checkAdmin;
        if (infoDTO .getUser().getAccountId().equals("admin")){
            checkAdmin = "isAdmin";
        } else {
            checkAdmin = "notAdmin";
        }
        model.addAttribute("checkAdmin", checkAdmin);
        //累加阅读数
        infoService.incView(infoID);
        model.addAttribute("info", infoDTO);
        model.addAttribute("comments", comments);
        model.addAttribute("relatedQuestions", relatedQuestions);
        return "info";
    }
}
